<?php
namespace common\components;
use yii\base\InvalidConfigException;
use yii\db\QueryInterface;
/**
 * 仅为了添加默认每页记录数及按id倒序
 * @author peter
 *
 */
class ActiveDataProvider extends \yii\data\ActiveDataProvider{

    public $model;
    public function __construct($config = []){
        if (empty($config['pagination'])) {
            $config['pagination'] = ['defaultPageSize'=>100];
        }
        if(!isset($config['pagination']['defaultPageSize'])){
            $config['pagination']['defaultPageSize'] = 100;
        }
        if(!isset($config['pagination']['pageSizeLimit'])){
            $config['pagination']['pageSizeLimit'] = [1,1000];
        }
        $modelClass = $config['query']->modelClass;
        $this->model = new $modelClass();
        if (empty($config['sort']) || !isset($config['sort']['defaultOrder'])) {
            $primaryKey = $modelClass::primaryKey();
            $sortOptions = [];
            foreach ($primaryKey as $key){
                $sortOptions[$key] = SORT_DESC;
            }
            $config['sort']['defaultOrder'] = $sortOptions;
        }
        if(!isset($config['sort']['attributes'])){
            $sortAttributes = [];
            foreach ($this->model->attributes() as $key => $attribute) {
                if(is_numeric($key)){
                    $sortAttributes[$attribute] = [
                        'asc' => [$attribute => SORT_ASC],
                        'desc' => [$attribute => SORT_DESC],
                        'label' => $this->model->getAttributeLabel($attribute),
                    ];
                }else{
                    $sortAttributes[$key] = [
                        'asc' => [$attribute => SORT_ASC],
                        'desc' => [$attribute => SORT_DESC],
                        'label' => $this->model->getAttributeLabel($attribute),
                    ];
                }
            }
            $config['sort']['attributes'] = $sortAttributes;
        }
        parent::__construct($config);
    }

    protected function prepareTotalCount(){
        if (!$this->query instanceof QueryInterface) {
            throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.');
        }
        $query = clone $this->query;
        if(!$query->where && method_exists($this->model, 'getTotalRecords')){
            return (int) $query->max('id');
        }
        return (int) $query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db);
    }
}

?>
